﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.Office.Interop.Excel;

namespace RESP_IIWaterAssessment
{
    public partial class FinancePlanReportForm : Form
    {
        public FinancePlanReportForm()
        {
            InitializeComponent();
        }

        int regID, avpID, lossType;
        const string catFactLossType = "FactLossType";

        private void FinancePlanReportForm_Load(object sender, EventArgs e)
        {
            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                chbRegion.Checked = true;
                cbRegion.Enabled = chbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;
                //toolStrip1.Visible = false;
            }

            string[] month;
            if (InformationClass.Lang)
                month = new string[] { "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" };
            else
                month = new string[] { "Январ", "Феврал", "Март", "Апрел", "Май", "Июн", "Июл", "Август", "Сентябр", "Октябр", "Ноябр", "Декабр" };

            for (int i = 1; i <= 12; i++)
            {
                var m = new
                {
                    ID = i,
                    Name = month[i - 1]
                };
                cbMonth.Items.Add(m);
            }
            cbMonth.DisplayMember = "Name";
            cbMonth.ValueMember = "ID";

            for (int i = 1991; i < 2100; i++)
            {
                cbYear.Items.Add(i);
            }
            cbMonth.SelectedIndex = cbMonth.FindStringExact(month[DateTime.Now.Month - 1]);
            cbYear.SelectedIndex = cbYear.FindStringExact(DateTime.Now.Year.ToString());

            cbFactLossType.SelectedIndexChanged -= cbFactLossType_SelectedIndexChanged;

            cbFactLossType.DataSource = UtilClass.FillCBCategory(catFactLossType);

            cbFactLossType.DisplayMember = "Name";
            cbFactLossType.ValueMember = "ID";
            cbFactLossType.SelectedIndex = -1;
            cbFactLossType.Text = string.Empty;
            cbFactLossType.SelectedIndexChanged += new EventHandler(cbFactLossType_SelectedIndexChanged);
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                cbAVP.Enabled = true;
                regID = Convert.ToInt32(cbRegion.SelectedValue);
                cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
                cbAVP.DataSource = UtilClass.FillAVP(regID);
                cbAVP.ValueMember = "ID";
                cbAVP.DisplayMember = "Name";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;
                cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
            }
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
                //int m = cbMonth.SelectedIndex + 1;
                //int y = Convert.ToInt32(cbYear.Text);
                //ShowState(avpID, m, y);
                //avpIncome = DBClass.AVPIncomes.Where(wh => wh.AVPID == avpID && )
            }
        }

        private void chbRegion_CheckedChanged(object sender, EventArgs e)
        {
            cbRegion.Enabled = chbRegion.Checked;
        }

        private void chbAVP_CheckedChanged(object sender, EventArgs e)
        {
            cbAVP.Enabled = chbAVP.Checked;
        }

        private void chbYear_CheckedChanged(object sender, EventArgs e)
        {
            cbYear.Enabled = chbYear.Checked;
            if (!chbYear.Checked)
            {
                chbMonth.Checked = false;
            }
        }

        private void chbMonth_CheckedChanged(object sender, EventArgs e)
        {
            if (chbYear.Checked)
                cbMonth.Enabled = chbMonth.Checked;
            else
                chbMonth.Checked = cbMonth.Enabled = false;

        }

        private void chbFactLoss_CheckedChanged(object sender, EventArgs e)
        {
            cbFactLossType.Enabled = chbFactLoss.Checked;
        }

        private void cbFactLossType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (avpID > 0 && cbFactLossType.SelectedIndex >= 0)
            {
                lossType = Convert.ToInt32(cbFactLossType.SelectedValue);
            }
        }

        private void buttonShow_Click(object sender, EventArgs e)
        {
            dgvFinPlanReport.Columns.Clear();

            SqlConnection con = new SqlConnection(DBClass.ConStr);
            SqlCommand com = new SqlCommand("FinancePlanReport", con);
            com.CommandType = CommandType.StoredProcedure;

            com.Parameters.Add("@Lang", SqlDbType.Bit).IsNullable = true;
            com.Parameters.Add("@RegionID", SqlDbType.Int).IsNullable = true;
            com.Parameters.Add("@AVPID", SqlDbType.Int).IsNullable = true;
            com.Parameters.Add("@FactLossType", SqlDbType.Int).IsNullable = true;
            com.Parameters.Add("@Year", SqlDbType.Int).IsNullable = true;
            com.Parameters.Add("@Date", SqlDbType.SmallDateTime).IsNullable = true;

            com.Parameters["@Lang"].Value = InformationClass.Lang;

            if (chbRegion.Checked && regID > 0)
                com.Parameters["@RegionID"].Value = regID;
            else
                com.Parameters["@RegionID"].Value = DBNull.Value;

            if (chbAVP.Checked && avpID > 0)
                com.Parameters["@AVPID"].Value = avpID;
            else
                com.Parameters["@AVPID"].Value = DBNull.Value;

            if (chbAVP.Checked && avpID > 0)
            {
                int y = Convert.ToInt32(cbYear.Text);
                com.Parameters["@Year"].Value = y;
            }
            else
                com.Parameters["@Year"].Value = DBNull.Value;

            if (chbFactLoss.Checked && lossType > 0)
                com.Parameters["@FactLossType"].Value = lossType;
            else
                com.Parameters["@FactLossType"].Value = DBNull.Value;

            if (chbMonth.Checked)
            {
                int m = cbMonth.SelectedIndex + 1;
                int y = Convert.ToInt32(cbYear.Text);

                com.Parameters["@Date"].Value = new DateTime(y, m, 1);
            }
            else
                com.Parameters["@Date"].Value = DBNull.Value;

            System.Data.DataTable tab = new System.Data.DataTable("Rep");
            SqlDataAdapter adapter = new SqlDataAdapter(com);
            try
            {
                adapter.Fill(tab);
                dgvFinPlanReport.DataSource = tab;
                AddColumns();

                if (InformationClass.Lang)
                {
                    dgvFinPlanReport.Columns["Date"].HeaderText = "Дата";
                    dgvFinPlanReport.Columns["RegionName"].HeaderText = "Район";
                    dgvFinPlanReport.Columns["AverageCost"].HeaderText = "Средняя стоимость";
                    dgvFinPlanReport.Columns["AVPName"].HeaderText = "АВП";
                    dgvFinPlanReport.Columns["Area"].HeaderText = "Площадь";
                    dgvFinPlanReport.Columns["FullLossAmount"].HeaderText = "Общий объём оказанных услуг, (тыс.сум)";
                }
                else
                {
                    dgvFinPlanReport.Columns["Date"].HeaderText = "Сана";
                    dgvFinPlanReport.Columns["RegionName"].HeaderText = "Туман номи";
                    dgvFinPlanReport.Columns["AverageCost"].HeaderText = "Сув узатиш бўйича хизматларнинг ўртача нарҳи";
                    dgvFinPlanReport.Columns["AVPName"].HeaderText = "СИУ номи";
                    dgvFinPlanReport.Columns["Area"].HeaderText = "Суғориладиган майдон";
                    dgvFinPlanReport.Columns["FullLossAmount"].HeaderText = "Амалда бажарилган хизматларнинг умумий ҳажми";
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(msgClass.msgNoData, msgClass.msgAchtung);
                dgvFinPlanReport.DataSource = null;
                dgvFinPlanReport.Columns.Clear();
            }
        }

        List<int> percentColIndex = new List<int>();

        int firstInd = 0, countColPerc = 0;

        private void AddColumns()
        {
            string[] losses = UtilClass.GetCategory(catFactLossType) as string[];
            percentColIndex = new List<int>();
            firstInd = 0;
            countColPerc = 0;

            if (dgvFinPlanReport.ColumnCount > 0)
            {
                firstInd = dgvFinPlanReport.ColumnCount;

                for (int i = 0; i < dgvFinPlanReport.ColumnCount; i++)
                {
                    for (int j = 0; j < losses.Length; j++)
                    {
                        if (dgvFinPlanReport.Columns[i].Name == losses[j])
                        {
                            string name = dgvFinPlanReport.Columns[i].Name + "_Percent";
                            dgvFinPlanReport.Columns.Add(name, dgvFinPlanReport.Columns[i].Name + " %");
                            dgvFinPlanReport.Columns[name].DisplayIndex = dgvFinPlanReport.Columns[i].DisplayIndex + 1;
                            percentColIndex.Add(dgvFinPlanReport.Columns[name].DisplayIndex);
                            countColPerc++;
                            break;
                        }
                    }
                }

                if (dgvFinPlanReport.RowCount > 0)
                    AddPercent();
            }
        }

        private void AddPercent()
        {
            for (int row = 0; row < dgvFinPlanReport.RowCount; row++)
            {
                for (int i = 0; i < percentColIndex.Count; i++)
                {
                    try
                    {
                        dgvFinPlanReport[firstInd + i, row].Value = ((decimal)dgvFinPlanReport[firstInd - countColPerc + i, row].Value / (decimal)dgvFinPlanReport["FullLossAmount", row].Value * 100).ToString("N2");
                    }
                    catch
                    {
                        dgvFinPlanReport[firstInd + i, row].Value = "0.00";
                    }
                }
            }
        }

        private void buttonExcel_Click(object sender, EventArgs e)
        {
            if (dgvFinPlanReport.RowCount > 0)
            {
                MessageBox.Show(msgClass.msgWaiting, msgClass.msgAchtung);
                this.Cursor = Cursors.WaitCursor;
                GetReport();
                excelapp.Visible = true;
                this.Cursor = Cursors.Default;
            }
        }

        Sheets excelsheets;
        Worksheet excelworksheet;
        Microsoft.Office.Interop.Excel.Application excelapp;
        Workbook excelappworkbook;

        private void GetReport()
        {
            string[] losses = UtilClass.GetCategory(catFactLossType) as string[];

            excelapp = new Microsoft.Office.Interop.Excel.Application();
            excelapp.SheetsInNewWorkbook = 1;

            if (InformationClass.Lang)
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i21r17.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            else
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i21r17uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            excelappworkbook = excelapp.Workbooks[1];
            excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 

            int left = 3, top = 9;

            excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(1);

            excelworksheet.Cells.NumberFormat = "@";

            if (chbRegion.Checked)
                excelworksheet.Cells[4, 3] = cbRegion.Text;
            if (chbYear.Checked)
                excelworksheet.Cells[5, 3] = cbYear.Text;


            for (int i = 0; i < dgvFinPlanReport.Rows.Count; i++)
            {
                excelworksheet.Cells[i + top, 3] = dgvFinPlanReport[2, i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, 23]);

                excelworksheet.Cells[i + top, 4] = dgvFinPlanReport[0, i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, 4]);


                for (int j = 3; j < dgvFinPlanReport.Columns.Count; j++)
                {
                    excelworksheet.Cells[i + top, dgvFinPlanReport.Columns[j].DisplayIndex + left - 1] = dgvFinPlanReport[j, i].FormattedValue;
                    addBorder(excelworksheet.Cells[i + top, dgvFinPlanReport.Columns[j].DisplayIndex + left]);


                }
                //excelworksheet.Cells[i + top, 3] = UtilClass.GetRegionName(dgvAVPHarvest["AVPName", i].Value.ToString());
                //addBorder(excelworksheet.Cells[i + top, 3]);
                excelworksheet.Cells[i + top, 2] = i + 1;
                addBorder(excelworksheet.Cells[i + top, 2]);

            }

            int n = 0;
            for (int i = 0; i < dgvFinPlanReport.ColumnCount; i++)
            {

                for (int k = 0; k < losses.Length; k++)
                {
                    if (dgvFinPlanReport.Columns[i].Name == losses[k])
                    {
                        excelworksheet.get_Range(excelworksheet.Cells[7, i + 2 + n], excelworksheet.Cells[7, i + 3 + n]).Merge(Type.Missing);
                        excelworksheet.Cells[7, i + n + 2] = losses[k];
                        addBorder(excelworksheet.Cells[7, i + n + 2]);
                        addBorder(excelworksheet.Cells[7, i + n + 3]);

                        excelworksheet.Cells[8, i + n + 2] = "Тыс.Сум";
                        addBorder(excelworksheet.Cells[8, i + n + 2]);
                        excelworksheet.Cells[8, i + n + 3] = "%";
                        addBorder(excelworksheet.Cells[8, i + n + 3]);

                        n++;
                    }
                }
            }

            excelworksheet.Columns.AutoFit();
            excelworksheet.Select(1);
        }

        private void addBorder(object p)
        {
            Range tmpRange = excelworksheet.get_Range(p, p);
            tmpRange.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            if (dgvFinPlanReport.RowCount > 0)
                PrintDGV.Print_DataGridView(dgvFinPlanReport);
        }

    }
}
